import React, { Suspense } from 'react';
import { createBrowserRouter, RouterProvider, Navigate, Outlet } from 'react-router-dom';
import { Spin } from 'antd';
import Layout from '../layouts/Layout';
// 懒加载页面组件
const HomePage = React.lazy(() => import('../pages/home/HomePage'));
const BookmarkPage = React.lazy(() => import('../pages/bookmark/BookmarkPage'));
const FavoritePage = React.lazy(() => import('../pages/favorite/FavoritePage'));
const SoftwarePage = React.lazy(() => import('../pages/software/SoftwarePage'));
const BlogPage = React.lazy(() => import('../pages/blog/BlogPage'));
const NotFoundPage = React.lazy(() => import('../pages/NotFoundPage'));

// 加载中组件
const LoadingSpinner = () => (
  <div style={{
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '200px'
  }}>
    <Spin size="large" />
  </div>
);

// 路由包装器，用于懒加载
const LazyWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <Suspense fallback={<LoadingSpinner />}>
    {children}
  </Suspense>
);

// 路由配置
export const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout><Outlet /></Layout>,
    children: [
      {
        index: true,
        element: (<LazyWrapper> <HomePage />  </LazyWrapper>),
      },
      {
        path: 'bookmark',
        element: (<LazyWrapper> <BookmarkPage />          </LazyWrapper>),
      },
      {
        path: 'bookmark/:id',
        element: (<LazyWrapper>            <BookmarkPage />          </LazyWrapper>),
      },
      {
        path: 'favorites',
        element: (
          <LazyWrapper>
            <FavoritePage />
          </LazyWrapper>
        ),
      },
      {
        path: 'favorites/:id',
        element: (
          <LazyWrapper>
            <FavoritePage />
          </LazyWrapper>
        ),
      },
      {
        path: 'software',
        element: (
          <LazyWrapper>
            <SoftwarePage />
          </LazyWrapper>
        ),
      },
      {
        path: 'software/:id',
        element: (
          <LazyWrapper>
            <SoftwarePage />
          </LazyWrapper>
        ),
      },
      {
        path: '404',
        element: (
          <LazyWrapper>
            <NotFoundPage />
          </LazyWrapper>
        ),
      },
      { path: 'blog', element: <LazyWrapper><BlogPage /></LazyWrapper> },
      { path: 'blog/:id', element: <LazyWrapper><BlogPage /></LazyWrapper> },
      { path: 'blog/category/:category', element: <LazyWrapper><BlogPage /></LazyWrapper> },
      // 404 页面
      { path: '*', element: <Navigate to="/404" replace /> },
    ],
  },
]);

// 路由提供者组件
const AppRouter: React.FC = () => {
  return <RouterProvider router={router} />;
};

export default AppRouter;
